<template>
  <el-form :model="formData" :rules="formRules" size="small" :inline="false" label-width="100px" ref="ruleFormRef">
    <el-form-item label="主题" prop="title">
      <el-input v-model="formData.title" placeholder="请填写主题" maxlength="32" size="small"/>
    </el-form-item>
    <el-form-item label="员工" prop="staffId">
      <el-select v-model="formData.staffId" placeholder="请选择员工" size="small" filterable>
        <el-option v-for="item in staffList" :key="item.id" :value="item.id" :label="item.name"/>
      </el-select>
    </el-form-item>
    <el-form-item label="合同编号" prop="contractCode">
      <el-input v-model="formData.contractCode" placeholder="请填写合同编号" maxlength="32" size="small"/>
    </el-form-item>
    <el-form-item label="合同公司" prop="contractCompanyId">
      <el-select v-model="formData.contractCompanyId" placeholder="请选择合同公司" size="small" filterable>
        <el-option v-for="item in companyList" :key="item.id" :value="item.id" :label="item.name"/>
      </el-select>
    </el-form-item>
    <el-form-item label="合同类型" prop="contractType">
      <el-select v-model="formData.contractType" placeholder="请选择合同类型" size="small">
        <el-option v-for="item in dictMap['StaffContractType']" :key="item.value" :value="item.value" :label="item.name"/>
      </el-select>
    </el-form-item>
    <el-form-item label="合同日期" prop="occurDate">
      <el-date-picker
          v-model="contractDateRange"
          type="daterange"
          size="small"
          start-placeholder="请选择开始日期"
          end-placeholder="请选择到期日期"
          value-format="YYYY-MM-DD"
          @change="dateChange"/>
    </el-form-item>
    <el-form-item label="优先度">
      <el-radio-group v-model="formData.priority" size="small">
        <el-radio :label="0" size="small">普通</el-radio>
        <el-radio :label="1" size="small">高</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="备注信息" prop="remark">
      <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请填写备注信息" size="small"/>
    </el-form-item>
  </el-form>
</template>

<script>
// 合同 OA_CONTRACT
import {onMounted, reactive, toRefs, ref, watch} from 'vue'
import {getSelectorData} from '/@/api/oa/staff'
import {getDictByCodes} from '/@/api/sys/dict'
import {getContractCompanySelector} from '/@/api/oa/contractCompany'
import {formatDate} from '/@/utils/formatTime'
import { useCalendarConfig } from '/@/stores/calendar';
import { storeToRefs } from 'pinia';
import {homeApi} from '/@/api/home/index'

export default {
  name: 'Contract',
  props: {
    selectTime: {
        type: String,
        default: null
    },
    editId: {
      type: String,
      default: null
    }
  },
  setup(props) {
    const { editId } = toRefs(props)
    const homeCalendar = homeApi()
    const storesCalendarConfig = useCalendarConfig();
    const { eventForm } = storeToRefs(storesCalendarConfig)
    const state = reactive({
      formData: {
        title: '合同',
        staffId: null,
        contractCode: null,
        contractCompanyId: null,
        contractType: null,   // 合同类型 字典StaffContractType
        occurDate: null,    // 合同开始日期
        endDate: null,    // 合同到期日期
        remark: null,
        state: 2,           // 状态 -1草稿 0未开始 1进行中 2已完成 3已退回  4已取消 5已撤回
        priority: 0        // 优先级 0普通 1重要
      },
      formRules: {
        title: {required: true, message: '请填写主题', trigger: 'blur'},
        staffId: {required: true, message: '请选择员工', trigger: 'change'},
        contractCode: {required: true, message: '请填写合同编号', trigger: 'blur'},
        contractCompanyId: {required: true, message: '请选择合同公司', trigger: 'change'},
        contractType: {required: true, message: '请选择合同类型', trigger: 'change'},
        occurDate: {required: true, message: '请选择合同日期', trigger: 'change'}
      },
      contractDateRange: [],
      dictMap: {},
      staffList: [],
      companyList: [],  // 合同公司
      originForm: {}
    })
    const ruleFormRef = ref()
    const getStaffData = async () => {
      try {
        const res = await getSelectorData()
        state.staffList = res.data
      } catch (e) {
        console.log(e)
      }
    }
    const getCompanyList = async () => {
      try {
        const res = await getContractCompanySelector()
        state.companyList = res.data
      } catch (e) {
        console.log(e)
      }
    }
    const dateChange = val => {
      if (val && val.length == 2) {
        state.formData.occurDate = val[0]
        state.formData.endDate = val[1]
      } else {
        state.formData.occurDate = state.formData.endDate = null
      }
    }
    watch(() => eventForm.value,
      val => {
        if(editId.value && val) {
          // 编辑
          nextTick(() => {
            const data = val
            if(!data) return
            state.originForm = data
            for(let params in data.info){
              // 拿出info里面的数据
              if(state.formData.hasOwnProperty(params)) {
                state.formData[params] = data.info[params]
              }
            }
            for(let key in data) {
              // 列表里面的数据
              if(state.formData.hasOwnProperty(key)) {
                state.formData[key]= data[key]
              }
            }
            if(data.actionStartTime && data.actionEndTime) {
              // 时间组合
              state.contractDateRange = [data.actionStartTime, data.actionEndTime]
            }
          })
        }
      }        
    )
    onMounted(() => {
      // 合同编号 毫秒时间戳+5位随机串
      if(!editId.value) {
        state.formData.contractCode = formatDate(new Date(), 'YYYYmmddHHMMSSsss') + Math.round(Math.random() * (99999 - 10000) + 10000)
      }
      getDictByCodes(['StaffContractType']).then(res => state.dictMap = res.data)
      getStaffData()
    })
    const submit = () => {
      if (!ruleFormRef) return
      return new Promise(async (resolve, reject) => {
        await ruleFormRef.value.validate((valid, fields) => {
          if (valid) {
            if(editId.value) {
              // 编辑
              for(let key in state.formData){
                if(state.originForm.hasOwnProperty(key)){
                  state.originForm[key] = state.formData[key]
                }
                if(state.originForm.info.hasOwnProperty(key)){
                  state.originForm.info[key] = state.formData[key]
                }
              }
              storesCalendarConfig.setEventForm(state.originForm)
              resolve('edit') 
            }else{
              homeCalendar.addContract(state.formData).then(res => {
                if (res.code === 0) {
                  reset()
                  context.emit('closeForm')
                  resolve()
                }
              }).catch(e => reject(e))
            }
          }else{
            console.log('error submit!', fields)
          }
        })
      })
    }
    const reset = () => {
      if (!ruleFormRef) return
      ruleFormRef.value.resetFields()
    }
    return {
      ...toRefs(state),
      getStaffData,
      getCompanyList,
      dateChange,
      submit,
      reset,
      ruleFormRef
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
